<template>
  <div class="app-container">
    <el-row v-if="tplid">
      <el-select
        v-model="filterVal"
        @change="filterChange"
        multiple
        collapse-tags
        style="margin-left: 20px"
        placeholder="执行情况、疾病筛选"
      >
        <el-option
          v-for="item in filterLs"
          :key="item.value"
          :label="item.text"
          :value="item.value"
        >
        </el-option>
      </el-select>

      <el-button round @click="openTpl" style="margin: 5px">打开模板</el-button>
    </el-row>

    <el-row>
      <el-table
        v-loading="loading"
        :data="resultLs"
        highlight-current-row
        style="width: 100%"
        max-height="700"
        :cell-class-name="cellClassName"
        :span-method="objectSpanMethod"
        :summary-method="getSummaries"
        @current-change="handleCurrentChange"
        show-summary
        border
      >
        <el-table-column type="index" width="50" fixed> </el-table-column>
        <el-table-column prop="路径名称" label="疾病名称" width="250" fixed>
        </el-table-column>

        <el-table-column prop="类型" label="项目分类" width="100" fixed>
        </el-table-column>
        <el-table-column prop="名称" label="项目小分类" width="250" fixed>
          <template slot-scope="scope">
            <el-tooltip
              class="item"
              effect="dark"
              :content="scope.row.限制说明"
              placement="right"
              v-if="scope.row.限制说明 && !scope.row.名称1"
            >
              <span style="color: red">{{ scope.row.名称 }}</span>
            </el-tooltip>
            <span v-else>{{ scope.row.名称 }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="名称1" label="名称" width="200">
          <template slot-scope="scope">
            <el-tooltip
              class="item"
              effect="dark"
              placement="right"
              v-if="scope.row.限制说明 || scope.row.药品说明"
            >
              <div slot="content" v-html="名称1_fmt(scope.row)"></div>
              <span style="color: red">{{ scope.row.名称1 }}</span>
            </el-tooltip>
            <span v-else>{{ scope.row.名称1 }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="必选">
          <template slot-scope="scope">
            <span>{{ scope.row.执行性质 ? "√" : "" }}</span>
          </template>
        </el-table-column> -->

        <!--

           :filters="filterLs"
          :filter-method="filter结果含义"
        -->
        <el-table-column prop="结果含义" label="执行情况">
          <template slot-scope="scope">
            <el-tooltip
              popper-class="atooltip"
              v-if="scope.row.oos"
              placement="top"
            >
              <div slot="content">
                <div v-for="(it2, i) in scope.row.oos" v-bind:key="i">
                  {{ it2.XMMC }}
                </div>
              </div>
              <span>{{ scope.row.结果含义 }}</span>
            </el-tooltip>
            <span v-else>{{ scope.row.结果含义 }}</span>
          </template>
        </el-table-column>

        <el-table-column
          prop="不符合适应症金额"
          label="不符合适应症金额"
          width="200"
        >
        </el-table-column>
        <el-table-column
          v-for="(it, i) in dayCols"
          :prop="it.data"
          :label="it.label"
          :title="it.title"
          v-bind:key="i"
        >
          <template slot-scope="scope">
            <el-tooltip
              :content="
                (scope.row[`amount_${scope.column.property}`] || 0).toString()
              "
              placement="top"
              popper-class="atooltip"
            >
              <span>{{ scope.row[scope.column.property] }}</span>
            </el-tooltip>
          </template>

          <template slot="header">
            <span v-html="it.label"></span>
          </template>
        </el-table-column>
        <el-table-column prop="备注" label="备注" width="200">
        </el-table-column>

        <el-table-column prop="金额" label="金额"> </el-table-column>

        <el-table-column :formatter="totalFormatter" label="费用小计">
        </el-table-column>

        <el-table-column prop="扣减分值" label="扣减分值"> </el-table-column>
      </el-table>
    </el-row>

    <el-row>
      <el-tabs v-model="activeName">
        <el-tab-pane label="基本信息" name="basicInfo">
          <el-descriptions title="基本信息">
            <el-descriptions-item label="姓名">
              <span>{{ userinfo.patname }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="住院号">
              <span>{{ userinfo.fno }}</span>
            </el-descriptions-item>

            <el-descriptions-item label="总费用">
              <span
                v-bind:class="
                  costChangeCss(userinfo.expended, totalObj.平均费用)
                "
                >{{ userinfo.cost }}/{{ totalObj.平均费用.toFixed(2) }}</span
              >
            </el-descriptions-item>
            <el-descriptions-item label="床日">
              <span
                v-bind:class="costChangeCss(userinfo.bed, totalObj.平均床日)"
                >{{ userinfo.bed }}/{{ totalObj.平均床日 }}</span
              >
            </el-descriptions-item>
            <el-descriptions-item label="药品费">
              <span
                v-bind:class="
                  costChangeCss(userinfo.expended, totalObj.平均药品费)
                "
                >{{ userinfo.expended }}/{{ totalObj.平均药品费 }}</span
              >
            </el-descriptions-item>
            <el-descriptions-item label="检验费"
              ><span
                v-bind:class="
                  costChangeCss(
                    userinfo.surveyfee,
                    totalObj.平均检验费,
                    '检验费'
                  )
                "
                >{{ userinfo.surveyfee }}/{{ totalObj.平均检验费 }}</span
              ></el-descriptions-item
            >
            <el-descriptions-item label="检查费">
              <span
                v-bind:class="
                  costChangeCss(userinfo.examfee, totalObj.平均检查费, '检查费')
                "
                >{{ userinfo.examfee }}/{{ totalObj.平均检查费 }}</span
              >
            </el-descriptions-item>
            <el-descriptions-item label="手术费">
              <span
                v-bind:class="
                  costChangeCss(userinfo.optfee, totalObj.平均手术费)
                "
                >{{ userinfo.optfee }}/{{ totalObj.平均手术费 }}</span
              >
            </el-descriptions-item>
            <el-descriptions-item label="耗材费">
              <span
                v-bind:class="
                  costChangeCss(userinfo.matfee, totalObj.平均耗材费)
                "
                >{{ userinfo.matfee }}/{{ totalObj.平均耗材费 }}</span
              >
            </el-descriptions-item>

            <el-descriptions-item label="主诊断">
              {{ userinfo.discode }}-{{ userinfo.disname }}
            </el-descriptions-item>

            <el-descriptions-item label="病组"
              >{{ userinfo.drgcode }}-{{
                userinfo.drgname
              }}</el-descriptions-item
            >

            <el-descriptions-item label="手术"
              >{{ userinfo.optcode }}-{{
                userinfo.optname
              }}</el-descriptions-item
            >

            <el-descriptions-item label="路径"
              >{{ patwayinfo.ID }}-{{ patwayinfo.名称 }}</el-descriptions-item
            >

            <el-descriptions-item label="路径版本">{{
              vn(userinfo.drgcode)
            }}</el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
        <el-tab-pane label="诊断信息" name="zdjl">
          <el-table
            :data="zdljData"
            border
            :row-class-name="诊断信息_RowClassName"
            :span-method="objectSpanMethod2"
            style="width: 100%"
          >
            <el-table-column prop="ZDLX" label="诊断类型" width="80">
            </el-table-column>
            <el-table-column prop="JBBM" label="疾病编码" width="180">
            </el-table-column>
            <el-table-column prop="ZDMS" label="疾病名称" width="300">
            </el-table-column>
            <el-table-column prop="特征费用" label="特征费用" width="300">
            </el-table-column>

            <el-table-column :formatter="状态_fmt" label="状态" width="300">
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="费用信息" name="costInfo">
          <el-row>
            <el-select
              v-model="costSummaryFilterValue"
              placeholder="费用类别"
              @change="ResetCostSummary"
            >
              <el-option
                v-for="item in costSummaryFilter"
                :key="item.value"
                :label="item.text"
                :value="item.value"
              >
              </el-option>
            </el-select>

            <el-select
              style="margin-left: 10px"
              v-model="费用等级Val"
              placeholder="费用等级"
              @change="ResetCostSummary"
            >
              <el-option
                v-for="item in 费用等级Ls"
                :key="item.value"
                :label="item.text"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-row>
          <el-row>
            <el-table
              :data="
                costSummaryLs.slice(
                  (disePathsPage - 1) * disePathsSize,
                  disePathsPage * disePathsSize
                )
              "
              show-summary
              :summary-method="costSummary_sum"
              style="width: 100%"
            >
              <el-table-column prop="医保项目编码" label="医保项目编码">
              </el-table-column>
              <el-table-column prop="项目名称" label="项目名称">
              </el-table-column>
              <el-table-column prop="费用类别" label="费用类别">
              </el-table-column>
              <el-table-column prop="费用等级" label="费用等级">
              </el-table-column>
              <el-table-column prop="适用疾病" label="适用疾病">
              </el-table-column>
              <el-table-column prop="费用属性" label="费用属性">
              </el-table-column>
              <el-table-column prop="单位" label="单位"> </el-table-column>
              <el-table-column prop="数量" label="数量"> </el-table-column>
              <el-table-column prop="金额" label="金额"> </el-table-column>
            </el-table>

            <div class="block">
              <el-pagination
                @size-change="disePathsbasicCostHandleSizeChange"
                @current-change="disePathsbasicCostCurrentChange"
                :current-page="disePathsPage"
                :page-sizes="[5, 10, 20, 50, 100, 200, 300, 400]"
                :page-size="disePathsSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="costSummaryLsTotal"
              >
              </el-pagination>
            </div>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-row>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
// import { UserModule } from '@/store/modules/user'
import {
  patResult,
  patDayInfo,
  projectOutScope,
  patientinfo,
  zdjl,
  sljl,
  costSummary,
} from "@/api/patient";
import { drugInstru } from "@/api/commonApi";
import { tplExists, GetTplById, DisePath, stdCost, ljdir } from "@/api/pathway";
import { privateDecrypt } from "crypto";
import { getVersionName } from "@/utils/Utils";

@Component({
  name: "evaluate",
})
export default class extends Vue {
  private created() {
    //初始化天数字段，解决BUG
    this.dayCols = Array.from(new Array(1).keys()).map((it: any) => ({
      label: `第${it + 1}天出院日`,
      data: `day${it + 1}`,
      day: it,
    }));

    let id: any = this.$route.query.id || "1079886-1";

    this.loadPatResult(id);
  }

  private content_fmt(限制说明: string, 药品说明: string) {
    let ls = [];
    if (限制说明) ls.push(`限制说明:${限制说明}`);
    if (药品说明) ls.push(`药品说明：${药品说明}`);
    return ls.join("<br/>");
  }
  private disePathsSize = 5;
  private disePathsPage = 1;
  private disePathsbasicCostHandleSizeChange(val: number) {
    this.disePathsSize = val;
    this.disePathsPage = 1;
  }
  private disePathsbasicCostCurrentChange(val: number) {
    this.disePathsPage = val;
    //this.selectRow();
  }
  private currentRow: any = undefined;
  private handleCurrentChange(row: any) {
    this.currentRow = row;
  }

  private 状态_fmt(r: any) {
    // if('0'==r.并发症状态||!r.并发症状态){
    //   return '0';
    // }

    if ("1" == r.并发症状态) {
      return "MCC";
    }

    if ("2" == r.并发症状态) {
      return "CC";
    }
    if ("3" == r.并发症状态) return "排除";
    return "";
  }

  private 诊断信息_RowClassName(r: any) {
    return r.row.ZDCX == "1" && ["出院诊断", "手术"].includes(r.row.ZDLX)
      ? "maincode"
      : "";
  }

  private vn(code: string) {
    if (!code) return "";
    return getVersionName(code);
  }

  private 名称1_fmt(row: any) {
    let ls = [];
    if (row.限制说明) {
      ls.push(
        "<span class='xzsmhead'>【限制说明】</span><span class='xzsmbody'>" +
          row.限制说明 +
          "</span>"
      );
    }
    if (row.药品说明) {
      ls.push(
        "<span class='syzhead'>【适应症】</span><br/><span class='syzbody'>" +
          row.药品说明.split(/[。；;]/gi).join("。<br/>") +
          "</span>"
      );
    }
    return ls.join("<br/>");
  }

  private totalFormatter(row: any, column: any, cellValue: any, index: number) {
    let sum = 0;
    if (this.rowAndColumn[index] > 0) {
      let len = this.rowAndColumn[index];
      for (let i = index; i < index + len; i++) {
        let obj = this.resultLs[i];
        sum += obj.金额;
        // Object.keys(obj)
        //   .filter((it: string) => it.startsWith("amount_day"))
        //   .forEach((k: string) => {
        //     if (obj[k]) sum += obj[k];
        //   });
      }
    }

    this.userinfo[row.类型] = sum;

    //console.log(this.totalObj);

    return sum.toFixed(2);
  }

  private megerCell: any;

  //合并行
  objectSpanMethod(arg: {
    row: any;
    column: any;
    rowIndex: number;
    columnIndex: number;
  }) {
    //if (!arg.column.property) return;
    //合并大分类
    if (arg.column.property === "类型" || arg.column.label == "费用小计") {
      if (this.rowAndColumn[arg.rowIndex]) {
        let rowNum = this.rowAndColumn[arg.rowIndex];
        return {
          rowspan: rowNum,
          colspan: rowNum > 0 ? 1 : 0,
        };
      }
      return {
        rowspan: 0,
        colspan: 0,
      };
    }
    if (arg.column.property == "名称") {
      if (this.rowRoomColumn[arg.rowIndex]) {
        let roomNum = this.rowRoomColumn[arg.rowIndex];
        return {
          rowspan: roomNum,
          colspan: roomNum > 0 ? 1 : 0,
        };
      }
      return {
        rowspan: 0,
        colspan: 0,
      };
    }

    if (arg.column.label == "必选") {
      if (this.必选组合合并[arg.rowIndex]) {
        let rowNum = this.必选组合合并[arg.rowIndex];
        return {
          rowspan: rowNum,
          colspan: rowNum > 0 ? 1 : 0,
        };
      }
      return {
        rowspan: 0,
        colspan: 0,
      };
    }
  }
  //设置单元格的样式
  private cellClassName(arg: any) {
    if (!arg.column.property) return;

    //匹配、漏做、漏复查、不符合适应症、非最佳选择
    let colorMap: any = {
      匹配: "green",
      漏做: "yellow",
      漏复查: "gray",
      不符合适应症: "red",
      非最佳选择: "blue",
      非最优: "blue",
      超范围: "cfw",
    };
    if (arg.column.property === "结果含义") {
      let v = arg.row[arg.column.property];
      if (!v) return;
      return colorMap[v];
    }
    return "";
  }

  private resultLs: Array<any> = [];

  private dayCols: Array<any> = [];

  private getDaysBetween(dateString1: string, dateString2: string) {
    var startDate = Date.parse(dateString1);
    var endDate = Date.parse(dateString2);
    var days = (endDate - startDate) / (1 * 24 * 60 * 60 * 1000);
    return days;
  }

  private userinfo: any = { cost: 0 };
  private totalObj: any = { 平均费用: 0 };
  //做超20%以上红色，不足80%蓝色，剩余的黑色
  private costChangeCss(val1: number, val2: number, val3: string) {
    if (val1 == 0) return "";

    let f = val1 / val2;
    if (val3 == "检查费" || val3 == "检验费") {
      return { costColorBlue: f < 0.8 };
    }
    return { costColorRed: f > 1.2 };
  }

  private activeName = "basicInfo";

  private zdljData: [] | undefined = [];

  private zdljMegerCells: Array<number> = [];
  /**
   * 诊断记录
   */
  private async zdljLs(id: string) {
    //诊断记录
    let zdjlData: any = await zdjl({ id: id });
    zdjlData = zdjlData.data;

    //手术记录
    let sljlData: any = await sljl({ id: id });
    sljlData = sljlData.data;

    let banzdlx = 4;
    let yszdlx = 3;
    //病案
    let tmpLs: any = zdjlData.filter((it: any) => it.JLLY == banzdlx);

    if (tmpLs.length == 0) {
      tmpLs = zdjlData.filter((it: any) => it.JLLY == yszdlx);
    }

    tmpLs.sort((a: any, b: any) => {
      let zdlid = parseInt(a.ZDLXID) - parseInt(b.ZDLXID);
      if (zdlid == 0) {
        return parseInt(a.ZDCX) - parseInt(b.ZDCX);
      }

      return zdlid;
    });

    let tmpslLs: [] = sljlData.filter((it: any) => it.JLLY == banzdlx);

    if (tmpslLs.length == 0) {
      tmpslLs = sljlData.filter((it: any) => it.JLLY == yszdlx);
    }

    tmpslLs.sort((a: any, b: any) => {
      return parseInt(a.SSCX) - parseInt(b.SSCX);
    });

    tmpslLs.forEach((it: any, i: number) => {
      let o: any = { ZDLX: "手术", JBBM: it.SSBM, ZDMS: it.SSMC, ZDCX: i + 1 };
      tmpLs.push(o);
    });

    //诊断记录合并
    let pos: number = 0;
    for (var i = 0; i < tmpLs.length; i++) {
      if (i === 0) {
        // 如果是第一条记录（即索引是0的时候），向数组中加入１
        this.zdljMegerCells.push(1);
        pos = 0;
      } else {
        if (tmpLs[i].ZDLX === tmpLs[i - 1].ZDLX) {
          // 如果storeName相等就累加，并且push 0
          this.zdljMegerCells[pos] += 1;
          this.zdljMegerCells.push(0);
        } else {
          // 不相等push 1
          this.zdljMegerCells.push(1);
          pos = i;
        }
      }
    }

    this.zdljData = tmpLs;
  }

  private objectSpanMethod2(arg: {
    row: any;
    column: any;
    rowIndex: number;
    columnIndex: number;
  }) {
    if (arg.column.label == "诊断类型") {
      if (this.zdljMegerCells[arg.rowIndex]) {
        let rowNum = this.zdljMegerCells[arg.rowIndex];
        return {
          rowspan: rowNum,
          colspan: rowNum > 0 ? 1 : 0,
        };
      }
      return {
        rowspan: 0,
        colspan: 0,
      };
    }
  }

  //模板ID
  private tplid: string = "";
  private openTpl() {
    if (this.currentRow?.版本id) {
      this.$router.push({
        path: "/clinicalpathway/designer",
        query: {
          tid: this.currentRow?.版本id,
        },
      });
    } else {
      this.$message({
        type: "info",
        message: "请选择要操作的行",
      });
    }
  }

  private patwayinfo: any = {};
  private filterVal: any = "";
  private filterLs: Array<{ text: string; value: string }> = [];

  private filterChange(vals: Array<any>) {
    let tmps = [];

    if (vals && vals.length > 0) {
      tmps = this.resultLsCache.filter((it: any) => {
        return vals.includes(it.结果含义);
      });
    } else {
      tmps = JSON.parse(JSON.stringify(this.resultLsCache));
    }

    //查看与主诊断相关滴
    if (vals.includes("mainCode") && vals.length == 1) {
      tmps = this.resultLsCache.filter((it: any) => {
        return it.路径名称.indexOf(this.userinfo.discode) > -1;
      });
    } else if (vals.includes("mainCode")) {
      tmps = tmps.filter((it: any) => {
        return it.路径名称.indexOf(this.userinfo.discode) > -1;
      });
    }
    //与主诊断无关滴
    if (vals.includes("nmainCode") && vals.length == 1) {
      tmps = this.resultLsCache.filter((it: any) => {
        return it.路径名称.indexOf(this.userinfo.discode) == -1;
      });
    } else if (vals.includes("nmainCode")) {
      tmps = tmps.filter((it: any) => {
        return it.路径名称.indexOf(this.userinfo.discode) == -1;
      });
    }

    this.mergerCellCompute(
      tmps,
      vals && vals.length > 0 ? {} : this.objMegerCells
    );

    this.resultLs = tmps;
  }
  private filter结果含义(value: any, row: any, column: any) {
    const property = column["property"];
    return row[property] === value;
  }
  private async loadPatResult(id: string) {
    this.loading = true;
    try {
      let pData: any = await patientinfo({ id: id });
      pData = pData.data;
      this.userinfo = pData;

      let sdCost: any = await stdCost({ code: pData.drgcode });
      sdCost = sdCost.data;
      if (sdCost && sdCost.length > 0) {
        this.totalObj = sdCost[0];
      }

      let r = await ljdir({ code: pData.discode });

      this.patwayinfo = r.data || {};

      let data: any = await patResult({ id: id });
      let tmpls = data.data;

      this.filterLs = Array.from(
        new Set(tmpls.map((it: any) => it.结果含义))
      ).map((it: any) => ({ text: it, value: it }));
      this.filterLs.push({ text: "主诊断相关", value: "mainCode" });
      this.filterLs.push({ text: "非主诊断相关", value: "nmainCode" });

      let dayData: any = await patDayInfo({
        id: id,
        pid: 0,
        t: 1,
      });
      dayData = dayData.data;
      tmpls.forEach((it: any) => {
        let k = it.ID1 || it.ID;
        let ls: Array<any> = dayData.filter((it2: any) => {
          return it2.评估ID == k;
        });
        ls.forEach((it2: any) => {
          it[`day${it2.住院天数}`] = "√";
          it[`amount_day${it2.住院天数}`] = it2.金额;
        });
      });
      let maxDay: number = 0;

      if (dayData.length > 0) {
        maxDay = Math.max(...dayData.map((it: any) => it.住院天数));
      }

      this.dayCols = Array.from(new Array(maxDay).keys()).map((it: any) => {
        let m: any = {
          data: `day${it + 1}`,
          title: `amount_day${it + 1}`,
          day: it,
        };

        let l = `第${it + 1}天`;

        if (it == 0) {
          l = `第${it + 1}天<div style='color:red;'>入院日</div>`;
        }

        if (pData.optDate) {
          let optDay =
            this.getDaysBetween(
              pData.itime.split(" ")[0],
              pData.optDate.split(" ")[0]
            ) + 1;

          if (it + 1 == optDay) {
            l = `第${it + 1}天<div style='color:red;'>手术日</div>`;
          }
        }

        if (it + 1 == maxDay) {
          l = `第${it + 1}天`;

          if (!this.userinfo.zy) {
            l += "<div style='color:red;'>出院日</div>";
          }
        }

        m.label = l;

        return m;
      });
      //超范围显示药品名称
      let 项目IDS = tmpls
        .filter((it: any) => it.结果含义)
        .map((it: any) => it.项目ID);
      if (项目IDS.length > 0) {
        let formData = new FormData();
        formData.append("id", id);
        formData.append("ls", 项目IDS);
        let d: any = await projectOutScope(formData);
        d = d.data;
        tmpls.forEach((it: any) => {
          let ts = d.filter((it2: any) => it.项目ID == it2.项目ID);
          if (ts.length > 0) {
            let obj: any = {};
            ts.forEach((t: any) => {
              obj[t.XMMC] = t;
            });
            it.oos = Object.keys(obj).map((k: string) => obj[k]);
            //it.oos=ts;
          }
        });
      }

      this.tplid = tmpls[0]?.版本id;

      let tplData: any = await GetTplById({ id: this.tplid });
      tplData = tplData.data;

      //模板里的备注赋给当前结果
      tplData.data?.forEach((it: any) => {
        let ts = tmpls.filter((it2: any) => it2.项目ID == it.objid?.trim());
        ts.forEach((it2: any) => {
          it2.备注 = it.mark;
        });
      });

      let tplMetas = tplData.metas;

      //必选项合并

      tplMetas
        .filter((it: any) => it.备注 == "合并项目组")
        .forEach((it: any) => {
          if (!this.objMegerCells[it.字段名称])
            this.objMegerCells[it.字段名称] = [];
          this.objMegerCells[it.字段名称].push(it.字段值);
        });

      this.resultLs = tmpls;
      this.resultLsCache = tmpls;
      //药品说明
      let 药品名称s = this.resultLs
        .filter((it: any) => it.类型 == "药品")
        .map((it) => it.名称1);
      if (药品名称s.length > 0) {
        let d: any = await drugInstru(药品名称s);
        d = d.data;
        this.resultLs.forEach((it: any) => {
          let ts: any = d.filter((it2: any) => it.名称1 == it2.名称);
          if (ts.length > 0) {
            it.药品说明 = ts[0].适用范围;
          }
        });
      }
      this.mergerCellCompute(tmpls, this.objMegerCells);
    } finally {
      this.loading = false;
    }

    setTimeout(() => {
      this.zdljLs(id);
      this.costSummary(id);
    }, 10);
  }

  private costSummaryFilter: Array<any> = [];
  private costSummaryFilterValue = "";

  private costSummaryLsTotal: number = 0;

  private 费用等级Ls: Array<any> = [];

  private 费用等级Val = "";
  /**
   * 病人费用信息
   */
  private costSummaryLs: Array<any> = [];
  private costSummaryLsCache: [] = [];
  private async costSummary(id: string) {
    let d = await costSummary({ id: id });
    this.costSummaryLsCache = d.data;
    let set: Set<string> = new Set();
    let set1: Set<string> = new Set();
    this.costSummaryLsCache.forEach((it: any) => {
      set.add(it.费用类别);
      set1.add(it.费用等级);
    });
    this.costSummaryFilter = [
      { text: "费用类别(所有)", value: "" },
      ...Array.from(set).map((it: any) => ({
        text: it,
        value: it,
      })),
    ];

    this.费用等级Ls = [
      { text: "费用等级(所有)", value: "" },
      ...Array.from(set1).map((it: any) => ({
        text: it,
        value: it,
      })),
    ];

    this.costSummaryLs = JSON.parse(JSON.stringify(this.costSummaryLsCache));
    this.costSummaryLsTotal = this.costSummaryLs.length;
  }

  // private filter费用类别(value: any, row: any) {
  //   console.log(row.费用类别, value, row.费用类别 === value);
  //   this.ResetCostSummary((row: any) => row.费用类别 === value);
  //   return false;
  //   //return row.费用类别 === value;
  // }

  private costSummaryTime: any = 0;
  private ResetCostSummary(val: any) {
    //console.log(this.costSummaryFilterValue, this.费用等级Val);

    let tms: any = this.costSummaryLsCache;

    if (this.costSummaryFilterValue) {
      tms = tms.filter((it: any) => it.费用类别 == this.costSummaryFilterValue);
    }

    if (this.费用等级Val) {
      tms = tms.filter((it: any) => it.费用等级 == this.费用等级Val);
    }
    this.disePathsPage = 1;
    this.costSummaryLs = tms;
    this.costSummaryLsTotal = tms.length;
  }

  private costSummary_sum(param: any) {
    const { columns, data } = param;
    const sums: any = [];
    columns.forEach((column: any, index: number) => {
      if (index === 0) {
        sums[index] = "总计";
        return;
      }

      if (column.property == "数量" || column.property == "金额") {
        const values = this.costSummaryLs.map((item: any) =>
          Number(item[column.property])
        );
        if (!values.every((value: any) => isNaN(value))) {
          sums[index] = values.reduce((prev: any, curr: any) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);

          if (column.property == "金额") {
            sums[index] = sums[index].toFixed(2) + " 元";
          }
        }
      }
    });

    return sums;
  }

  private objMegerCells: any = {};

  private resultLsCache: Array<any> = [];

  private loading: boolean = false;

  private rowAndColumn: Array<number> = [];
  private rowRoomColumn: Array<number> = [];
  private 必选组合合并: Array<number> = [];

  private mergerCellCompute(tmpLs: Array<any>, objMegerCells: any = null) {
    let pos: number = 0;
    let posT: number = 0;
    this.rowAndColumn = [];
    this.rowRoomColumn = [];

    for (var i = 0; i < tmpLs.length; i++) {
      if (i === 0) {
        // 如果是第一条记录（即索引是0的时候），向数组中加入１
        this.rowAndColumn.push(1);
        pos = 0;
        this.rowRoomColumn.push(1);
        posT = 0;
      } else {
        if (tmpLs[i].类型 === tmpLs[i - 1].类型) {
          // 如果storeName相等就累加，并且push 0
          this.rowAndColumn[pos] += 1;
          this.rowAndColumn.push(0);
          if (tmpLs[i].名称 === tmpLs[i - 1].名称) {
            // 如果roomName相等就累加，并且push 0
            this.rowRoomColumn[posT] += 1;
            this.rowRoomColumn.push(0);
          } else {
            this.rowRoomColumn.push(1);
            posT = i;
          }
        } else {
          // 不相等push 1
          this.rowAndColumn.push(1);
          pos = i;
          this.rowRoomColumn.push(1);
          posT = i;
        }
      }
    }

    // if (!objMegerCells) {
    //   this.必选组合合并 = [];
    //   return;
    // }

    //========必选合并算法============
    //1.获取合并项的下标
    let objMegerIndes: Array<any> = [];
    Object.keys(objMegerCells).forEach((k: any) => {
      let m = objMegerCells[k];
      //必须要有1个以上才有必要合并
      let matchedLs = tmpLs.filter(
        (it: any) => m.includes(it.名称) || m.includes(it.名称1)
      );
      if (matchedLs.length > 1) {
        objMegerIndes.push(matchedLs.map((it: any) => tmpLs.indexOf(it)));
      }
    });
    //2.按下标填充合并标识列表
    objMegerIndes.forEach((v: any) => {
      let start = v[0];
      let end = v[v.length - 1];

      this.必选组合合并[start] = end - start + 1;
      for (let i = start + 1; i <= end; i++) {
        this.必选组合合并[i] = 0;
      }
    });
    //3.补齐其他项
    for (var i = 0; i < tmpLs.length; i++) {
      if (this.必选组合合并[i] != 0 && !this.必选组合合并[i]) {
        this.必选组合合并[i] = 1;
      }
    }
  }

  /**
  获取版本号
   */
  private vm(code: string) {
    return getVersionName(code);
  }

  private getSummaries(param: { data: any; columns: Array<any> }) {
    let sums: any = [];

    let columns = param.columns;

    columns.forEach((c: any, i: number) => {
      if (i == 0) {
        sums[i] = "合计";
        return sums;
      }
      if (c.label == "费用小计" || c.label == "金额") {
        let sum = 0;
        this.resultLs.forEach((it: any) => {
          sum += it.金额;
          // Object.keys(it)
          //   .filter((k: string) => k.startsWith("amount_day"))
          //   .forEach((k: string) => {
          //     if (it[k]) sum += it[k];
          //   });
        });
        sums[i] = sum.toFixed(2);
      }
      if (c.property == "不符合适应症金额" || c.label == "扣减分值") {
        let sum = 0;
        this.resultLs.forEach((it: any) => {
          if (it[c.property]) sum += parseFloat(it[c.property]);
        });
        sums[i] = sum.toFixed(2);
      }
      if (c.property?.startsWith("day")) {
        let sum = 0;
        this.resultLs.forEach((it: any) => {
          if (it[`amount_${c.property}`])
            sum += parseFloat(it[`amount_${c.property}`]);
        });
        sums[i] = sum.toFixed(2);
      }
    });
    return sums;
  }
}
</script>

<style lang="scss" scope>
.el-table__cell {
  text-align: center !important;
}

.xzsmhead,
.syzhead {
  font-weight: bold;
  font-size: 14px;
}

.xzsmbody,
.syzbody {
  letter-spacing: 1px;
}

.costColorRed {
  color: red;
}
.costColorBlue {
  color: blue;
}

.green {
  background-color: rgba(90, 170, 90, 0.7);
}
.blue {
  background-color: rgb(96, 96, 170, 0.7);
}
.red {
  background-color: rgb(201, 30, 30, 0.7);
}
.yellow {
  background-color: rgb(209, 211, 70);
}
.gray {
  background-color: rgb(209, 177, 136);
}
.cfw {
  background-color: rgb(117, 97, 70, 0.7);
}
.maincode {
  color: blue;
  font-weight: bold;
}
.el-tooltip__popper {
  max-width: 600px;
}

.gray,
.green,
.blue,
.red,
.cfw,
.yellow {
  font-weight: bold;
}

.atooltip {
  background-color: rgb(146, 25, 45) !important;
  font-size: 16px;
}
</style>
